"""
WordPress数据适配器
用于将原始数据转换为WordPress文章数据模型
"""

import random
from typing import Dict, Any
from .data_adapter import DataAdapter
from models.wordpress_article_data import WordPressArticleData
from utils.logger_config import get_logger


class WordPressDataAdapter(DataAdapter):
    """
    WordPress数据适配器，将原始数据转换为WordPress文章数据模型
    """
    
    def __init__(self):
        super().__init__()
        self.logger = get_logger(__name__)
    
    def convert(self, source_data: Dict[str, Any]) -> WordPressArticleData:
        """
        将原始数据转换为WordPress文章数据模型
        
        Args:
            source_data: 包含title、content、images、local_images、image_mapping等字段的原始数据
            
        Returns:
            WordPressArticleData实例
        """
        # 提取基本信息
        title = source_data.get('title', '')
        content = source_data.get('content', '')
        url = source_data.get('url', '')
        
        # 将文章内容中的图片URL替换为本地路径
        image_mapping = source_data.get('image_mapping', {})
        if image_mapping and content:
            for img_url, local_path in image_mapping.items():
                # 只有当本地路径与原始URL不同时才替换
                if local_path != img_url:
                    content = content.replace(img_url, local_path)
        
        # 创建WordPress文章数据模型
        wordpress_data = WordPressArticleData(
            title=title,
            content=content,
            url=url
        )
        
        # 设置图片信息
        wordpress_data.images = source_data.get('images', [])
        wordpress_data.local_images = source_data.get('local_images', [])
        wordpress_data.image_mapping = image_mapping  # 保存图片URL到本地路径的映射
        
        # 设置其他WordPress特定字段
        wordpress_data.status = source_data.get('status', 'publish')
        # 确保使用有效的分类ID，如果未提供则使用默认分类ID 1
        category_id = source_data.get('category_id', 1)
        wordpress_data.category_id = category_id
        wordpress_data.tags = source_data.get('tags', [])
        wordpress_data.featured_media_id = source_data.get('featured_media_id')
        wordpress_data.publish_date = source_data.get('publish_date')
        
        return wordpress_data